package com.juzhencms.apps.busi.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.FileUtil;
import com.juzhencms.apps.base.common.util.ObjectUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class TemplateService extends CommonService{
	
	@Autowired
	private MenuService menuService;
	
	
	public String getTemplatesPath() {
		return Config.getValue("external-templates-path");
	}
	
	
	
	/**
	 * 根据模板目录名获取模板配置
	 * @param templatePath
	 * @return
	 */
	public Map getConfig(String templatePath) {
		String templatesPath=getTemplatesPath();
		String initDataFilePath=templatesPath+"/"+templatePath+"/config.json";
		File initDataFile=new File(initDataFilePath);
		if(initDataFile.exists() && initDataFile.isFile()) {
			try {
				Map configData=JSON.parseObject(FileUtil.getTextContents(initDataFile.getAbsolutePath(),"UTF-8"),LinkedHashMap.class,Feature.OrderedField);
				return configData;
			} catch (IOException e) {
				log.error("读取模板配置失败"+initDataFile.getAbsolutePath(),e);
			}
		}
		log.info("模板配置文件不存在"+initDataFile.getAbsolutePath());
		return null;
	}
	
	/**
	 * 根据模板目录名及目录中的文件名获取文件存储到数据库的url目录（相对于file目录）
	 * @param filename
	 * @return
	 */
	public String getUrlPath(String templatePath,String filename) {
		return "{templates}/"+templatePath+"/"+filename;
	}
	
	public boolean initTemplateSite(int siteId,String templateCode,boolean addTestData) {
		//获取模板配置文件
		Map template=this.getJdbcDao().queryRow("select * from "+DBTable.template+" where del_flag=0 and code=? limit 0,1", new Object[] {templateCode});
		if(template!=null) {
			Map configData=getConfig(template.get("template_path").toString());
			if(configData==null) {
				return false;
			}
			
			
			Map initData=(Map)configData.get("initData");
			//初始化栏目数据
			initMenuData(siteId,0,(List)initData.get("menu"),addTestData);
			//初始化广告数据
			initAdData(siteId,template.get("template_path").toString(),(List)initData.get("ad"));
			return true;
		}
		return false;
	}
	/**
	 * 递归创建栏目数据
	 * @param menuList
	 */
	public void initMenuData(int siteId,int parentId,List menuList,boolean addTestData) {
		if(menuList==null) {
			return;
		}
		
		for(int i=0;i<menuList.size();i++) {
			Map menuConfig=(Map)menuList.get(i);
			
			Map menuRecord=new HashMap();
			
			menuRecord.put("site_id", siteId);
			menuRecord.put("parent_id", parentId);
			menuRecord.put("name", menuConfig.get("name"));
			menuRecord.put("sub_name", menuConfig.get("sub_name"));
			menuRecord.put("alias", menuConfig.get("alias"));
			menuRecord.put("module", menuConfig.get("module"));
			menuRecord.put("menu_template", menuConfig.get("menu_template"));
			menuRecord.put("create_time", new Date());
			
			int menuId=this.getJdbcDao().addObj(DBTable.menu, menuRecord);
			menuRecord.put("id", menuId);
			//如果选择了添加测试数据，则同时添加测试数据
			if(addTestData) {
				menuService.addTestData(menuRecord);
			}
			
			if(menuConfig.get("children")!=null) {
				List subMenuList=(List)menuConfig.get("children");
				initMenuData(siteId,menuId,subMenuList,addTestData);
			}
			
		}
		
		
		
		
	}
	/**
	 * 创建广告位及广告数据
	 * @param adList
	 */
	public void initAdData(int siteId,String templatePath,List adList) {
		if(adList==null) {
			return;
		}
		
		for(int i=0;i<adList.size();i++) {
			Map adConfig=(Map)adList.get(i);
			
			Map adSpaceRecord=new HashMap();
			
			adSpaceRecord.put("site_id", siteId);
			adSpaceRecord.put("type", adConfig.get("type"));
			adSpaceRecord.put("name", adConfig.get("name"));
			adSpaceRecord.put("alias", adConfig.get("alias"));
			adSpaceRecord.put("width", adConfig.get("width"));
			adSpaceRecord.put("height", adConfig.get("height"));
			adSpaceRecord.put("create_time", new Date());
			
			int adSpaceId=this.getJdbcDao().addObj(DBTable.adSpace, adSpaceRecord);

			
			if(adConfig.get("data")!=null) {
				//添加广告数据
				List adDataList=(List)adConfig.get("data");
				for(int j=0;j<adDataList.size();j++) {
					Map adData=(Map)adDataList.get(j);
					if(adData!=null && adData.get("name")!=null && adData.get("file")!=null) {
						Map adRecord=new HashMap();
						
						adRecord.put("site_id", siteId);
						adRecord.put("space_id", adSpaceId);
						adRecord.put("name", adData.get("name"));
						
						//拼接广告图路径
						String adFile=getUrlPath(templatePath,adData.get("file").toString());
						
						adRecord.put("image", adFile);
						
						if(adData.get("link_url")!=null && !adData.get("link_url").toString().equals("")) {
							adRecord.put("link_url", adData.get("link_url"));
						}
						if(adData.get("link_target")!=null && !adData.get("link_target").toString().equals("")) {
							adRecord.put("link_target", adData.get("link_target"));
						}
						adRecord.put("create_time", new Date());
						this.getJdbcDao().addObj(DBTable.ad, adRecord);
					}
				}
			}
			
		}
		
		
	}


}
